<template>
  <div>
    <div class="user-msg-container">
      <el-form :model="userForm" label-width="100px">
        <!-- 登录名（只读） -->
        <el-form-item label="登录名">
          <el-input v-model="userForm.loginName" readonly></el-input>
        </el-form-item>

        <!-- 用户名 -->
        <el-form-item label="用户名">
          <el-input v-model="userForm.userName"></el-input>
        </el-form-item>

        <!-- 性别 -->
        <!-- 性别选择器 -->
        <el-form-item label="性别">
          <el-select v-model="userForm.sex" placeholder="请选择性别">
            <el-option label="男" :value="1"></el-option>
            <el-option label="女" :value="0"></el-option>
          </el-select>
        </el-form-item>

        <!-- 身份证号 -->
        <el-form-item label="身份证号">
          <el-input v-model="userForm.identityCode"></el-input>
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号">
          <el-input v-model="userForm.mobile"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="showPasswordDialog">修改密码</el-button>
          <el-button @click="showEmailDialog">修改邮箱</el-button>
        </el-form-item>
      </el-form>

      <!-- 密码修改弹窗 -->
      <el-dialog
        title="修改密码"
        :visible.sync="passwordDialogVisible"
        width="30%"
      >
        <el-form :model="passwordForm" ref="passwordForm">
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input
              type="password"
              v-model="passwordForm.oldPassword"
            ></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              type="password"
              v-model="passwordForm.newPassword"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              type="password"
              v-model="passwordForm.confirmPassword"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPassword">确认</el-button>
        </span>
      </el-dialog>

      <!-- 邮箱修改弹窗 -->
      <el-dialog
        title="修改邮箱"
        :visible.sync="emailDialogVisible"
        width="30%"
      >
        <el-form :model="emailForm" ref="emailForm">
          <el-form-item label="新邮箱" prop="email">
            <el-input v-model="emailForm.email" style="width: 60%"></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="captcha">
            <el-input v-model="emailForm.captcha" style="width: 60%">
              <el-button
                slot="append"
                @click="sendCaptcha"
                :disabled="captchaDisabled"
              >
                {{ captchaText }}
              </el-button>
            </el-input>
          </el-form-item>
        </el-form>
        <div v-if="UpdataEmailError">
          <span style="color: red">邮箱验证码错误</span>
        </div>
        <span slot="footer">
          <el-button @click="emailDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEmail">确认</el-button>
        </span>
      </el-dialog>

      <div v-if="isShowMsg" :style="{ color: isSuccess ? 'green' : 'red' }">
        <span>{{ updateMsg }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "UserMsg",
  data() {
    return {
      isSuccess: false,
      isShowMsg: false,
      UpdataEmailError: false,
      updateMsg: "",
      userForm: {
        id: "",
        loginName: "",
        userName: "",
        sex: "",
        identityCode: "",
        email: "",
        mobile: "",
        updateTime: "",
      },
      passwordDialogVisible: false,
      emailDialogVisible: false,
      captchaDisabled: false,
      captchaText: "获取验证码",
      countdown: 60,

      passwordForm: {
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      },

      emailForm: {
        email: "",
        captcha: "",
      },
    };
  },
  created() {
    this.fetchUserData();
  },
  methods: {
    async fetchUserData() {
      try {
        const response = await axios.get(`/api/user/getCurrentUser`);

        console.log("完整响应:", response);

        if (response.data?.code === 200) {
          this.userForm = response.data.easyBuyUser || {};
        } else {
          this.$message.warning(response.data?.msg || "数据格式异常");
        }
      } catch (error) {
        console.error("请求详情:", {
          url: error.config?.url,
          params: error.config?.params,
          response: error.response?.data,
        });
        this.$message.error("获取用户信息失败");
      }
    },

    async submitForm() {
      console.log("提交的用户数据:", {
        ...this.userForm,
        updateTime: undefined,
      });
      try {
        console.log(this.userForm);
        const idCardRegex = /(^\d{15}$)|(^\d{17}(\d|X|x)$)/;
        if (
          this.userForm.identityCode &&
          !idCardRegex.test(this.userForm.identityCode)
        ) {
          this.$message.error("请输入正确的身份证号码");
          return;
        }
        const mobileRegex = /^1[3-9]\d{9}$/;
        if (!mobileRegex.test(this.userForm.mobile)) {
          this.$message.error("请输入正确的11位手机号码");
          return;
        }

        const response = await axios.post(
          `/api/user/updateUser`,
          this.userForm
        );
        console.log("保存回调信息:", response);
        this.isShowMsg = true;
        this.isSuccess = true;
        this.updateMsg = "保存成功";
        // this.fetchUserData();
      } catch (error) {
        this.isShowMsg = "保存失败";
        console.error("操作失败:", error);
        // this.$message.error(
        //   "操作失败: " + (error.response?.data?.message || error.message)
        // );
      }
      // 这里添加实际提交到后端的代码
      // this.$message.success("保存成功");
    },
    showPasswordDialog() {
      this.passwordForm = {
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      };
      this.passwordDialogVisible = true;
      this.$nextTick(() => this.$refs.passwordForm?.clearValidate());
    },

    showEmailDialog() {
      this.emailForm = { email: "", captcha: "" };
      this.emailDialogVisible = true;
      this.$nextTick(() => this.$refs.emailForm?.clearValidate());
    },

    // 提交密码修改
    // 提交密码修改
    async submitPassword() {
      try {
        // 验证表单
        await this.$refs.passwordForm.validate();

        // 检查输入是否为空
        if (
          !this.passwordForm.oldPassword ||
          !this.passwordForm.newPassword ||
          !this.passwordForm.confirmPassword
        ) {
          this.$message.error("输入不能为空");
          return;
        }

        // 检查两次新密码是否一致
        if (
          this.passwordForm.newPassword !== this.passwordForm.confirmPassword
        ) {
          this.$message.error("两次新密码输入不一致");
          return;
        }

        // 检查新密码是否与旧密码相同
        if (this.passwordForm.oldPassword === this.passwordForm.newPassword) {
          this.$message.error("新密码不能与旧密码相同");
          return;
        }

        // 发送请求
        const response = await axios.post("/api/user/updatePassword", null, {
          params: {
            id: this.userForm.id,
            oldPassword: this.passwordForm.oldPassword,
            newPassword: this.passwordForm.newPassword,
          },
        });

        console.log("修改密码回调:", response);
        if (response.data.code === 200) {
          this.$message.success("密码修改成功");
          this.passwordDialogVisible = false;
          this.Exit();
        } else if (response.data.code === 500) {
          this.$message.error("密码修改失败:" + response.data.msg);
        }
      } catch (error) {
        console.error("密码修改失败:", error);
        if (
          error.response &&
          error.response.data &&
          error.response.data.code === 500
        ) {
          this.$message.error("旧密码错误，请重新输入");
        } else {
          this.$message.error("密码修改失败，请重试");
        }
      }
    },
    // 发送验证码
    async sendCaptcha() {
      try {
        if (this.isSendCaptcha) return; // 防止重复点击

       // 邮箱非空校验（发送验证码时额外校验，双重保障）
        if (!this.emailForm.email.trim()) {
          this.$message.error("请输入邮箱地址");
          return;
        }
        const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        if (!emailRegex.test(this.emailForm.email.trim())) {
          this.$message.error("邮箱格式错误");
          return;
        }

        const response = await axios.get("/api/email/getCaptcha", {
          params: { email: this.emailForm.email },
        });
        if (response.data.code === 200) {
          this.$message.success("验证码已发送");
          this.startCountdown(); // 启动倒计时
        } else {
          this.$message.error(response.data.msg || "验证码发送失败");
        }
      } catch (error) {
        console.error("发送验证码失败:", error);
        this.$message.error("发送验证码失败:" + (error.msg || error.message));
      }
    },
    // 倒计时
    startCountdown() {
      this.captchaDisabled = true;
      const timer = setInterval(() => {
        this.countdown--;
        this.captchaText = `${this.countdown}秒后重试`;
        if (this.countdown <= 0) {
          clearInterval(timer);
          this.captchaDisabled = false;
          this.captchaText = "获取验证码";
          this.countdown = 60;
        }
      }, 1000);
    },
    // 提交邮箱修改
    async submitEmail() {
      try {
        await this.$refs.emailForm.validate();

        const response = await axios.post("/api/user/updateEmail", null, {
          params: {
            id: this.userForm.id,
            email: this.emailForm.email,
            captcha: this.emailForm.captcha,
          },
        });
        console.log("修改邮箱回调:" + response);
        if (response.data.code === 200) {
          this.$message.success("邮箱修改成功");
          this.emailDialogVisible = false;
          this.fetchUserData(); // 刷新用户数据
        } else {
          this.UpdataEmailError = true;
        }
      } catch (error) {
        console.error("邮箱修改失败:", error);
      }
    },
    //退出登录操作
    async Exit() {
      try {
        const response = await axios.get(
          `/api/user/logout`
        );
        console.log("退出信息", response);
        if (response.data.code == 200) {
          sessionStorage.clear();
          // 如果当前不是首页，则跳转到首页
          if (this.$route.path !== "/") {
            this.$router.push("/");
          }
        }
      } catch (error) {
        console.log("退出失败信息：", error);
        alert("退出失败请重试");
      }
    },
  },
};
</script>

<style scoped>
.user-msg-container {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}
/* 限制表单项最大高度，防止拉伸 */
.user-msg-container /deep/ .el-form-item {
  max-height: 60px; /* 表单项正常高度约 40-60px */
  min-height: auto !important; /* 覆盖可能的最小高度 */
}

/* 确保输入框高度正常 */
.user-msg-container /deep/ .el-input__inner {
  height: 32px !important; /* 输入框高度（small 尺寸） */
}
</style>